$(document).ready(function(){
	
	$('input[type=checkbox]').click(checkTour);
	$('input:checked').each(checkTour);
	
	function checkTour(){
		id = $(this).attr('id');
		
		re = new RegExp('^tour-(on|off)-(\\d+)$');
		a = id.match(re);
		if ( !a || a.length != 3 ) return;
		
		id = 'tour-' + (a[1] == 'on' ? 'off' : 'on') + '-' + a[2];
		obj = $('#'+id);
		
		if ( $(this).attr('checked') ) {
			obj.attr('disabled','disabled');
			obj.parent().addClass('disabled');
		} else {
			obj.removeAttr('disabled');
			obj.parent().removeClass('disabled')
		}
	}
	
	if ( $('#country-off-0:checked').length ) cleanCountryChooser('off');
    if ( $('#country-on-0:checked').length ) cleanCountryChooser('on');
    
    $('#country-off-0').click(function(){ cleanCountryChooser('off'); });
    $('#country-on-0').click(function(){ cleanCountryChooser('on'); });
    
    function cleanCountryChooser(mid) {
    	$('#country-' + mid + '-element').find('.finder').remove();
    	$('#country-' + mid + '-id-element').addClass('hidden');
    };
    
    if ( $('#country-off-1:checked').length ) chooseCountry('off');
    if ( $('#country-on-1:checked').length ) chooseCountry('on');
    
    $('#country-off-1').click(function(){ chooseCountry('off'); });
    $('#country-on-1').click(function(){ chooseCountry('on'); });
    
    $('#country-off-id-element input:checked').click(removeCountry);
    $('#country-on-id-element input:checked').click(removeCountry);
    
    function removeCountry() {
    	$(this).parent().remove();
    }
    
    function chooseCountry(mid) {
    	var elem_id = '#country-'+mid+'-element';
    	if ( $(elem_id).find('.finder').length ) return;
    	$(elem_id).append($('<div class="finder" style="width: 200px"><input type="text" class="chooser" id="country-'+mid+'-chooser"/></div>'));
    	$('#country-' + mid + '-id-element').removeClass('hidden');
    	$('#country-' + mid + '-chooser').autocomplete({ 
    	    serviceUrl: '/reference/geo/complete',
    	    minChars: 2,
    	    delimiter: /(,|;)\s*/, // regex or character
    	    maxHeight: 400,
    	    width: 300,
    	    zIndex:  9999,
    	    deferRequestBy: 300, //miliseconds
    	    params: { level: 1 },
    	    noCache: false,
    	    onSelect: function(value, id) {
    	    	$('#country-'+mid+'-chooser').val('');
    	    	if ( $('#country-'+mid+'-id-'+id).length ) return;
    	    	
    	    	html =  '<label for="country-'+mid+'-id-'+id+'">';
				html += '<input type="checkbox" name="country_'+mid+'_id[]" id="country-'+mid+'-id-'+id+'" checked="checked" value="'+id+'"/>'+value;
				html += '</label>';
    	    	$('#country-'+mid+'-id-data').append($(html));
    	    	$('#country-'+mid+'-id-'+id).click(removeCountry);
    	    }
        });
    };
    
});
    